from datetime import datetime

from sqlalchemy import Column, String, DateTime

from app.database import BaseModel
from app.exceptions import AuthenticationFailed
from app.utils import sha256


class UserProfile(BaseModel):
    __tablename__ = "user_profile"

    nickname = Column(String(128), nullable=False, default="", comment="昵称")
    username = Column(String(), nullable=False, comment="用户名")
    password = Column(String(128), nullable=False, comment="密码")

    create_time = Column(DateTime, default=datetime.now)
    update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    def authenticate(self, password, raise_exception=True):
        hashed_password = sha256(password)
        if self.password != hashed_password:
            if raise_exception:
                raise AuthenticationFailed()
            else:
                return False
        return True
